<?php

class productActions extends sfActions {

    public function preExecute() {
        date_default_timezone_set(AppTools::TIMEZONE);
    }

    /**
     * Барааны жагсаалт
     *
     * @param sfWebRequest $request
     */
    public function executeList(sfWebRequest $request) {
        $categoryId = $request->getParameter('categoryId', null);
        $this->categoryId = $categoryId;
        $this->categories = CategoryTable::getForSelect(true);

        $manufacturerId = $request->getParameter('manufacturerId', null);
        $this->manufacturerId = $manufacturerId;
        $this->manufacturers = ManufacturerTable::getForSelect(true);

        $price = $request->getParameter('price', '');
        $this->price = $price;

        $priceSale = $request->getParameter('price_sale', '');
        $this->priceSale = $priceSale;

        $isActive = $request->getParameter('isActive', 1);
        $this->isActive = $isActive;

        $this->tableUrl = $this->generateUrl("product_list_data") . "?cat_id=$categoryId&man_id=$manufacturerId&is_active=$isActive&price=$price&price_sale=$priceSale";
        $this->updateUrl = $this->generateUrl("product_edit");
        $this->deleteUrl = $this->generateUrl("product_delete");
        $this->restoreUrl = $this->generateUrl("product_restore");
    }

    public function executeListData(sfWebRequest $request) {
        $start = $request->getParameter('jtStartIndex', 0);
        $length = $request->getParameter('jtPageSize', AppTools::DEFAULT_PER_PAGE);
        $sorting = $request->getParameter('jtSorting', "name ASC");
        $categoryId = $request->getParameter('cat_id', 0);
        $manufacturerId = $request->getParameter('man_id', 0);
        $price = $request->getParameter('price', '');
        $priceSale = $request->getParameter('price_sale', '');
        $isActive = $request->getParameter('is_active', ProductTable::ACTIVE);

        $res = ProductTable::getList(0, $categoryId, $manufacturerId, $isActive, $sorting, $start, $length, $price, $priceSale);

        $result = array();
        $result['Result'] = "OK";
        $result['Records'] = $res['rows'];
        $result['TotalRecordCount'] = $res['numrows'];
        echo json_encode($result);
        die();
    }

    /**
     * Бараа нэмэх/засах
     * 
     * @param sfWebRequest $request
     */
    public function executeUpdate(sfWebRequest $request) {
        $id = $request->getParameter('id');
        $uploaderUrl = $this->generateUrl('product_photo_uploader');
        $makeCoverUrl = $this->generateUrl('product_photo_set_cover');
        $user = $this->getUser();

        if ($id) {
            $product = ProductTable::retrieveByPK($id);
            if (!$product) {
                $user->setFlash('warning', 'Бараа олдсонгүй');
                $this->redirect($request->getReferer());
            }
            $uploaderUrl .= '?pid=' . $id;
            $flash = 'Амжилттай заслаа';
        } else {
            $product = new Product();
            $flash = 'Амжилттай нэмлээ';
        }

        $form = new ProductForm($product);

        if ($request->isMethod('post')) {
            $product = $request->getParameter('product');
            $form->bind($product);

            if ($product['photos']) {
                if ($id) {
                    $uploaderUrl .= '&pp=' . $product['photos'];
                } else {
                    $uploaderUrl .= '?pp=' . $product['photos'];
                }
            }

            if ($form->isValid()) {
                $form->save();
                $photosIds = explode(',', $product['photos']);
                foreach ($photosIds as $photoId) {
                    $photoId = (int) $photoId;
                    $photo = ProductPhotoTable::retrieveByPK($photoId);
                    if ($photo) {
                        $photo['product_id'] = $form->getObject()->getId();
                        $photo->save();
                    }
                }


                $user->setFlash('success', $flash);
                $this->redirect('@product_list');
            }
        }

        $this->form = $form;
        $this->id = $id;
        $this->product = $product;
        $this->uploaderUrl = $uploaderUrl;
        $this->makeCoverUrl = $makeCoverUrl;
    }

    /**
     * Төлөв өөрчлөх
     * 
     * @param sfWebRequest $request
     */
    public function executeChangeState(sfWebRequest $request) {
        $category = ProductTable::retrieveByPk($request->getParameter('id'));
        if ($category) {
            if ($category->is_active == ProductTable::ACTIVE) {
                $category->setIsActive(ProductTable::PASSIVE);
                $this->getUser()->setFlash('success', 'Амжилттай устгалаа');
            } elseif ($category->is_active == ProductTable::PASSIVE) {
                $category->setIsActive(ProductTable::ACTIVE);
                $this->getUser()->setFlash('success', 'Амжилттай сэргээлээ');
            }

            $category->save();
        } else {
            $this->getUser()->setFlash('error', 'Бараа олдсонгүй!');
        }

        $this->redirect('@product_list');
    }

    /**
     * Ajax . Ангиллаар барааны жагсаалтыг авах
     *
     * @param sfWebRequest $request
     */
    public function executeGetProduct(sfWebRequest $request) {
        $categoryId = (int) $request->getParameter('categoryId', 0);
        $productId = (int) $request->getParameter('productId', 0);
        $widgetName = $request->getParameter('widgetName', 'productId');
        $widgetId = $request->getParameter('widgetId', 'productId');

        $select = "<select id='$widgetId' name='$widgetName' >";
        $select .= '<option value="0">[Сонгох]</option>';

        $products = ProductTable::getForSelect($categoryId);
        foreach ($products AS $index => $value) {
            $selected = $index == $productId ? 'selected' : '';
            $select .= '<option value="' . $index . '" ' . $selected . ' >' . $value . '</option>';
        }

        $select .= '</select>';

        return $this->renderText($select);
    }

    public function executePhotoUploader(sfWebRequest $request) {
        $errorMessages = array(
            1 => 'Файлын хэмжээ дээд хязгаараас хэтэрсэн байна max(10Mb).',
            2 => 'Файлын хэмжээ дээд хязгаараас хэтэрсэн байна max(10Mb)',
            3 => 'Файл дутуу хуулагдсан байна',
            4 => 'Файл хуулагдсангүй',
            6 => 'Түр зуур хуулах зай хүрэлцсэнгүй. Та түр хүлээгээд дахин үзнэ үү',
            7 => 'HDD-рүү бичиж чадсангүй',
            8 => 'Файлын хуулалтыг серверээс зогсоолоо',
            'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini',
            'max_file_size' => 'Файл хэт том хэмжээтэй байна',
            'min_file_size' => 'Файл хэт бага хэмжээтэй байна',
            'accept_file_types' => 'Зөвшөөрөгдөөгүй файлын төрөл байна',
            'max_number_of_files' => 'Файлуудын тоо дээд хязгаарт хүрсэн байна',
            'max_width' => 'Зураг хэт өргөн байна',
            'min_width' => 'Зураг хэт нарийн байна',
            'max_height' => 'Зураг хэт өндөр байна',
            'min_height' => 'Зураг хэт намхан байна',
            'abort' => 'Хуулалтыг цуцлав',
            'image_resize' => 'Зургыг шахаж чадсангүй'
        );

        $uploadDir = sfConfig::get('sf_upload_dir');
        $imageUrl = AppTools::getFullUrl() . '/uploads';
        $options = array(
            'script_url' => $this->generateUrl('product_photo_uploader'),
            'upload_dir' => $uploadDir . AppTools::PRODUCT_IMAGE_PATH_ORIG,
            'upload_url' => $imageUrl . AppTools::PRODUCT_IMAGE_PATH_ORIG,
            'delete_type' => 'POST',
            'image_versions' => array(
                '' => array(
                    'auto_orient' => true,
                    'max_width' => AppTools::PRODUCT_IMAGE_SIZE,
                    'max_height' => AppTools::PRODUCT_IMAGE_SIZE
                ),
                'thumbnail' => array(
                    'upload_dir' => $uploadDir . AppTools::PRODUCT_IMAGE_PATH_THUMB,
                    'upload_url' => $imageUrl . AppTools::PRODUCT_IMAGE_PATH_THUMB,
                    //'crop' => true,
                    'max_width' => AppTools::PRODUCT_IMAGE_THUMB,
                    'max_height' => AppTools::PRODUCT_IMAGE_THUMB
                )
            )
        );

        $productPhotoHelper = new ProductPhotoHelper($options, true, $errorMessages);
        die();
    }

    /**
     * Үндсэн зураг болгох
     *
     * @param sfWebRequest $request 
     */
    public function executePhotoSetCover(sfWebRequest $request) {
        $photo = ProductPhotoTable::retrieveByPk($request->getParameter('id'));
        $productId = 0;
        if ($photo) {
            if ($photo->product_id) {
                ProductPhotoTable::unsetCover($photo->product_id);
                $productId = $photo->product_id;
            }

            $photo->setType(ProductPhotoTable::TYPE_MAIN);
            $photo->save();
        } else {
            die('0');
        }
        die('1');
    }

}
